﻿using System.Text;

namespace System.Windows.Forms
{
    /// <summary>
    /// ListView扩展功能
    /// </summary>
    public static class ExListView
    {
        /// <summary>
        /// 获取所有选中的项
        /// </summary>
        /// <param name="lvw">ListView对象</param>
        /// <returns>文本</returns>
        public static string GetSelectionText(this ListView lvw)
        {
            if (lvw == null) return string.Empty;
            StringBuilder strResult = new StringBuilder();
            //foreach会导致集合变成只读 这里用for
            for (int i = 0; i < lvw.SelectedItems.Count; i++)
            {
                try
                {
                    var item = lvw.SelectedItems[i];
                    strResult.Append(item.Text);
                    for (int j = 1; j < item.SubItems.Count; j++)
                    {
                        string strText = item.SubItems[j].Text;
                        strResult.Append("\t");
                        strResult.Append(strText);
                    }
                }
                catch
                {
                    break;
                }
                strResult.Append("\r\n");
            }
            return strResult.ToString();
        }

        /// <summary>
        /// 获取所有项
        /// </summary>
        /// <param name="lvw">ListView对象</param>
        /// <returns>文本</returns>
        public static string GetAllText(this ListView lvw)
        {
            if (lvw == null) return string.Empty;
            StringBuilder strResult = new StringBuilder();
            //foreach会导致集合变成只读 这里用for
            for (int i = 0; i < lvw.Items.Count; i++)
            {
                try
                {
                    var item = lvw.Items[i];
                    strResult.Append(item.Text);
                    for (int j = 1; j < item.SubItems.Count; j++)
                    {
                        string strText = item.SubItems[j].Text;
                        strResult.Append("\t");
                        strResult.Append(strText);
                    }
                }
                catch
                {
                    break;
                }
                strResult.Append("\r\n");
            }
            return strResult.ToString();
        }
    }
}
